package com.isunland.managesystem.ui;

import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.MyPlanProgressReplyListAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.ReplyOtherListBean;
import com.isunland.managesystem.entity.ReplyOtherOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import org.json.JSONException;

/**
 * 对象功能: 进展答复界面
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/5/2 10:30
 */
@SuppressWarnings("deprecation") public class MyPlanManageProgressReplyFragment
    extends BaseFragment {

  protected static final String EXTRA_EXCID =
      MyPlanManageProgressReplyActivity.class.getSimpleName() + "EXTRA_EXCID";
  //@BindView(R.id.lv_reply) ListView lvReply;
  @BindView(R.id.et_replyMessage) EditText etReplyMessage;
  @BindView(R.id.bt_sendMessage) Button btSendMessage;
  @BindView(R.id.ll_empty) LinearLayout llEmpty;
  @BindView(R.id.pr_reply) PullToRefreshListView prReply;

  private ArrayList<ReplyOtherListBean> replyList;
  private String excId;
  private int mPage;
  private MyPlanProgressReplyListAdapter madapter;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom("进展答复");
    replyList = new ArrayList<>();
    excId = getArguments().getString(EXTRA_EXCID);
    mPage = 1;
    //获取回复内容
    volleyPostReply();
  }

  private void volleyPostReply() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_REPLY_LIST);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("excId", excId);
    params.put("pageNumber", mPage + "");
    params.put("pageSize", "15");
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        prReply.onRefreshComplete();//停止刷新
        ReplyOtherOriginal original = new Gson().fromJson(arg0, ReplyOtherOriginal.class);
        if (original != null && Base.SUCCESS == original.getResult()) {
          ArrayList<ReplyOtherListBean> rows = original.getRows();
          if (mPage == 1 && rows.size() == 0) {
            llEmpty.setVisibility(View.VISIBLE);
            prReply.setEmptyView(llEmpty);
            return;
          } else {
            replyList.addAll(0, rows);
            if (madapter == null) {
              madapter = new MyPlanProgressReplyListAdapter(getActivity(), replyList);
              prReply.setAdapter(madapter);
            } else {
              madapter.notifyDataSetChanged();
            }
          }
          if (mPage == 1) {
            //滚动到底部
            prReply.getRefreshableView().setSelection(prReply.getRefreshableView().getBottom());
          }
        } else {
          ToastUtil.show("获取回复内容失败");
        }
      }
    });
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_plan_reply, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    int strokeWidth = 1; // 3dp 边框宽度
    int roundRadius = 5; // 8dp 圆角半径
    GradientDrawable gd = new GradientDrawable();//创建drawable
    gd.setColor(getResources().getColor(R.color.white));
    gd.setCornerRadius(roundRadius);
    gd.setStroke(strokeWidth, getResources().getColor(R.color.white));
    //etReplyMessage.setBackgroundDrawable(gd);

    //if (replyList.size() == 0) {
    //  llEmpty.setVisibility(View.VISIBLE);
    //  lvReply.setVisibility(View.GONE);
    //} else {
    //  llEmpty.setVisibility(View.GONE);
    //  lvReply.setVisibility(View.VISIBLE);
    //  MyPlanProgressReplyListAdapter madapter =
    //      new MyPlanProgressReplyListAdapter(getActivity(), replyList);
    //  lvReply.setAdapter(madapter);
    //  madapter.notifyDataSetChanged();
    //}

    //下拉刷新
    prReply.getLoadingLayoutProxy().setRefreshingLabel("正在载入...");
    //设置下拉标签
    prReply.getLoadingLayoutProxy().setPullLabel("下拉刷新...");
    //设置释放标签
    prReply.getLoadingLayoutProxy().setReleaseLabel("放开以刷新...");
    prReply.setMode(PullToRefreshBase.Mode.BOTH);
    prReply.getLoadingLayoutProxy().setLoadingDrawable(null);

    prReply.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
    prReply.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
      @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉
        mPage++;
        volleyPostReply();
      }

      @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉
        //mPage++;
        //volleyPostReply();
      }
    });
  }

  public static MyPlanManageProgressReplyFragment newInstance(String excId) {
    Bundle args = new Bundle();
    args.putString(EXTRA_EXCID, excId);
    MyPlanManageProgressReplyFragment fragment = new MyPlanManageProgressReplyFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @OnClick(R.id.bt_sendMessage) public void onClick() {
    //发送信息
    if (TextUtils.isEmpty(etReplyMessage.getText().toString())) {
      ToastUtil.show("请输入回复信息");
    } else {
      volleyPostSendMsg();
    }
  }

  private void volleyPostSendMsg() {
    //发消息是禁用按钮,避免重复发送.
    btSendMessage.setEnabled(false);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PLAN_REPLY);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("excId", excId);
    params.put("replyMsg", etReplyMessage.getText().toString());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        btSendMessage.setEnabled(true);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          btSendMessage.setEnabled(true);
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          if (message != null && SuccessMessage.SUCCESS.equalsIgnoreCase(message.getResult())) {
            ToastUtil.show(message.getMessage());
            etReplyMessage.setText("");
            mPage = 1;
            replyList.clear();
            volleyPostReply();
          } else if (message != null && SuccessMessage.FAILURE.equalsIgnoreCase(
              message.getResult())) {
            ToastUtil.show(message.getMessage());
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }
}
